package com.mrs.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.mrs.common.ResponseResult;
import com.mrs.common.enums.AppHttpCodeEnum;
import com.mrs.common.vo.CategoryVo;
import com.mrs.common.vo.ExcelCategoryVo;
import com.mrs.entity.Category;
import com.mrs.service.CategoryService;
import com.mrs.utils.BeanCopyUtils;
import com.mrs.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * description: CategoryController
 * date: 2022/9/11 22:25
 * author: MR.孙
 */
@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //查询所有分类接口
    @GetMapping("/listAllCategory")
    public ResponseResult<List<CategoryVo>> listAllCategory(){
        return categoryService.listAllCategory();
    }


    //导出分类信息excel的接口
    @PreAuthorize("@ps.hasPermissons('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){

        try {
            //设置响应头的header
            WebUtils.setDownloadHeader(response, "分类.xlsx");
            //查询需要导出的信息
            List<Category> categoryList = categoryService.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils
                    .copyBeanList(categoryList, ExcelCategoryVo.class);

            //把查询分类的信息写入到excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class)
                    .autoCloseStream(Boolean.FALSE)
                    //工作簿的名称
                    .sheet("分类导出")
                    .doWrite(excelCategoryVos);
        } catch (IOException e) {
            e.printStackTrace();
            //导出失败，返回前端错误信息
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
        }

    }

}
